package threading;

class MyBlockingQueue {
    //  定义成员
    //   头位置，尾位置，元素个数值
    volatile private int head = 0;
    volatile private int tail = 0;
    volatile private int size = 0;
    //  通过数组来实现一个队列
     volatile int[] items = new int[1000];
    // 实现put方法
    synchronized public void put(int item) throws InterruptedException {
        //  队列已满
        if (size == items.length) {
            this.wait();
        }
        if (tail == items.length) {
            tail = 0;
        }
        items[tail] = item;
        tail++;
        size++;
        this.notify();
    };
    // 实现take方法
    synchronized public Integer take() throws InterruptedException {
        //  队列为空
        if (size == 0) {
            this.wait();
        }
        int value = items[head];

        if (head == items.length) {
            head = 0;
        }
        head++;
        size--;
        this.notify();
        return value;
    };
}
public class TheadDemo9 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue();
        //  消费者
        Thread thread1 = new Thread( () -> {
            while (true){
                try {
                    int value = queue.take();
                    System.out.println("消费者： " + value);
                    System.out.println();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        } );
        //  生成者
        Thread thread2 = new Thread( () -> {
            int value = 0;
            while (true){
                try {
                    System.out.println("生产： " + value);
                    queue.put(value);
                    Thread.sleep(1000);
                    value++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        } );
        thread1.start();
        thread2.start();
        System.out.println("hello world");
    }
}
